<template>
	<view class="">
		<NavBar title="充值" :isShowLeftBtn="true">
		</NavBar>
	</view>
	<view class="content" :style="{minHeight:contentHeight}">
		<view class="main">
			<view class="sel_area flex_both m_b_40" @click="showCityPicker">
				<view class="flex">
					<view class="m_b_2 m_r_12" style="flex-shrink: 0;">
						<up-image :show-loading="true" src="/static/images/index/index_position.png" width="30rpx"
							height="40rpx"></up-image>
					</view>
					<view class="">
						<text class="f_28_0 u-line-1">
							{{curAddress}}
						</text>
					</view>
				</view>
				<view class="flex"
					style="width: 34rpx;height: 34rpx;border-radius: 50%;border: 2rpx solid #999999; justify-content: center;">
					<view class="m_l_2">
						<up-icon name="arrow-right" size="12" color="#999999"></up-icon>
					</view>
				</view>
			</view>
			<view class="row1">
				<view class="title m_t_20 m_b_32 flex_both">
					<text class="f_32_0_b">
						选择车型（{{role == 1?'集团用户':'普通用户'}}）
					</text>
					<view class="flex" style="padding: 10rpx; padding-right: 0;" @click="switchRole"
						v-if="userInfo.is_jituan_user">
						<text class="f_24_f m_b_4" style="color: #737272;">
							切换身份
						</text>
					</view>
				</view>
				<view class="row1_list flex">
					<view
						:class="['row1_item','m_b_14',index%3!==0?'m_l_14':'',index == row1ActiveIdx?'row1_item_active':'']"
						v-for="(item,index) in row1List" :key="index" @click="onClickRow1Item(index)"
						:style="{backgroundImage:index == row1ActiveIdx?`url(${row1ActiveBg})`:'',background:index == row1ActiveIdx?'':'#ffffff'}">
						<view class="m_b_14 flex" style="height: 74rpx;">
							<up-image :show-loading="true" :src="item.car_image" width="178rpx" height="52rpx"
								mode="widthFix"></up-image>
						</view>
						<view class="" style="max-width: 190rpx;">
							<text class="f_28_0_b u-line-1">
								{{item.car_name}}
							</text>
						</view>
					</view>
				</view>
			</view>
			<view class="row2">
				<view class="title m_t_50 m_b_32">
					<text class="f_32_0_b">
						充值金额
					</text>
				</view>
				<view class="row2_list" v-if="row1List.length>0">
					<view
						:class="['row2_item','m_b_24',index%4!==0?'m_l_18':'',index == row2ActiveIdx?'row2_item_active':'']"
						v-for="(item,index) in row1List[row1ActiveIdx].list" :key="index"
						@click="onClickRow2Item(index)"
						:style="{backgroundImage:index == row2ActiveIdx?`url(${row2ActiveBg})`:'',background:index == row2ActiveIdx?'':'#ffffff'}">
						<view class="row2_item_title" :style="{background:index == row2ActiveIdx?'':'#EFEEEE'}">
							<view class="m_b_6" style="max-width: 130rpx;">
								<text class="f_24_0 u-line-1" style="color: #1773E3;">
									{{row1List[row1ActiveIdx].car_name}}
								</text>
							</view>
						</view>
						<view class="row2_item_main">
							<view class="">
								<text class="f_32_0_b" style="color: #FA5A28;">
									{{item.price}}元
								</text>
							</view>
							<view class="">
								<text class="f_24_0" style="color: #343434;">
									洗车{{item.num}}次
								</text>
							</view>
						</view>
						<view class="mask_img">

						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="aticon_box flex_both">
			<view class="flex">
				<view class="m_b_4">
					<text class="f_24_0">
						支付：
					</text>
				</view>
				<view class="m_r_12">
					<text class="f_24_0" style="color: #FE2616;">
						¥
					</text>
				</view>
				<view class="" v-if="row1List.length>0">
					<text class="f_36_0" style="color: #FE2616">
						{{row1List[row1ActiveIdx].list[row2ActiveIdx].price}}
					</text>
				</view>
			</view>
			<view class="aticon_right">
				<view class="aticon_right_btn" @click="onShowConfirm">
					<text class="f_30_f">
						支付
					</text>
				</view>
			</view>
		</view>
	</view>
	<up-modal :show="confirmShow" title="提示" content='即将充值该套餐，是否继续？' :show-cancel-button="true" confirm-text="是"
		confirmColor="#F76D11" cancelText="否" @confirm="onConfirmShowfirm" @cancel="confirmShow = false"></up-modal>
	<up-picker ref="uCityPickerRef" :show="cityPickerShow" :columns="cityArr" keyName="name"
		@change="cityPickerChangeHandler" @cancel="cityPickerShow = false" @confirm="cityPickerConfirm"
		:defaultIndex="defaultIndex" confirmColor="#F76D11"></up-picker>
</template>
<script setup lang="ts">
	import { ref, reactive, getCurrentInstance } from "vue";
	import NavBar from "@/components/navbar.vue"
	import { roleInfoStore } from "@/stores/user";
	import { onLoad, onShow, onReady, onUnload } from "@dcloudio/uni-app";
	import QQMapWX from '@/common/qqmap-wx-jssdk.js'
	const { proxy } = getCurrentInstance()
	const contentHeight = ref('100vh')
	const statusBarHeight = ref(88)
	const row1ActiveBg = ref(proxy.$config.baseUrl + '/cz_row1_active.png')
	const row2ActiveBg = ref(proxy.$config.baseUrl + '/cz_row2_active.png')
	const roleInfo = roleInfoStore()
	const role = ref()
	onLoad(() => {
		uni.getSystemInfo({
			success: function (info) {
				statusBarHeight.value = (info.statusBarHeight + 44) * 2
				contentHeight.value = `calc(100vh - ${statusBarHeight.value + 80}rpx)`
			}
		});
		getUserInfo()
		role.value = roleInfo.role
	})
	onUnload(() => {
		clearInterval(timer.value)
	})
	const userInfo = ref({
		avatar: ''
	})
	const getUserInfo = async () => {
		let res = await proxy.$http('my.getUserInfo')
		let data = res.data
		userInfo.value = data
		roleInfo.is_normal_user = data.is_normal_user
		roleInfo.is_jituan_user = data.is_jituan_user
		roleInfo.car_normal_type_list = data.car_normal_type_list
		roleInfo.car_jituan_type_list = data.car_jituan_type_list
	}
	const row1List = ref([])
	const row1Imgs = ref([
		{ width: '178rpx', height: '52rpx', icon: '/static/images/index/cz_icon1.png' },
		{ width: '182rpx', height: '74rpx', icon: '/static/images/index/cz_icon2.png' },
		{ width: '176rpx', height: '74rpx', icon: '/static/images/index/cz_icon3.png' },
	])
	const getTaocan = async () => {
		let res = await proxy.$http('index.getTaocan', { is_jituan: role.value ? 1 : 0, ...positionInfo.value })
		let data = res.data
		row1List.value = data
	}
	const row1ActiveIdx = ref(0)
	const onClickRow1Item = (e) => {
		row1ActiveIdx.value = e
		row2ActiveIdx.value = 0
	}
	const row2ActiveIdx = ref(0)
	const onClickRow2Item = (e) => {
		row2ActiveIdx.value = e
	}
	const confirmShow = ref(false)
	const onShowConfirm = () => {
		if (row1List.value.length == 0) {
			return
		}
		confirmShow.value = true
	}
	const onConfirmShowfirm = () => {

		confirmShow.value = false
		buyOrder()
	}
	const isPay = ref(false)
	const buyOrder = async () => {
		let res = await proxy.$http('index.buyOrder', { taocan_id: row1List.value[row1ActiveIdx.value].list[row2ActiveIdx.value].taaocan_id, ...positionInfo.value })
		if (res.code == 1) {
			getPayResult(res.data)
			uni.showLoading({
				title: "支付中"
			})
			isPay.value = true
			// uni.navigateBack(1)
			uni.requestPayment({
				provider: 'wxpay', //wxpay微信 alipay支付宝
				...res.data, //订单数据 后台返回的数据  
				success: function (res) {
					console.log('支付成功');

				},
				// 参数有问题则抛出错误
				fail: function (err) {
					console.log('支付失败');
				},
			})
		}
	}
	const timer = ref(null)
	const getPayResult = (e) => {
		if (timer.value) {
			clearInterval(timer.value)
		}
		timer.value = setInterval(() => {
			getOrderInfo(e)
		}, 1500)
	}

	const getOrderInfo = async (e) => {
		let res = await proxy.$http('order.getOrderInfo', { order_id: e.order_id, carType: row1List.value[row1ActiveIdx.value].car_type })
		if (res.code == 1) {
			if (!res.data.orderInfo.pay_status) {
				isPay.value = false
			} else {
				isPay.value = true
				clearInterval(timer.value)
				uni.hideLoading()
				uni.$u.toast('支付成功')
				let oInfo = row1List.value[row1ActiveIdx.value].list[row2ActiveIdx.value]
				setTimeout(() => {
					uni.reLaunch({
						url: `/pages/index/rechargeSuccess?price=${oInfo.price}&num=${oInfo.num}&buy_reward=${res.data.orderInfo.buy_reward}`
					})
				})
			}
		}
	}
	const switchRole = () => {
		if (role.value == 1) {
			role.value = 0
			getTaocan()
		} else {
			role.value = 1
			getTaocan()
		}
		row1ActiveIdx.value = 0
		row2ActiveIdx.value = 0
	}

	// 区县相关
	const qqmapsdk = ref(null)
	onReady(() => {
		qqmapsdk.value = new QQMapWX({
			key: proxy.$config.txMapKey
		});
		getLoaction()
	})
	const longitude = ref()
	const latitude = ref()

	const getLoaction = () => {
		uni.getLocation({
			type: 'gcj02', // 返回可以用于uni.openLocation的经纬度
			success: function (res) {
				longitude.value = res.longitude
				latitude.value = res.latitude
				qqmapsdk.value.reverseGeocoder({
					location: {
						latitude: res.latitude,
						longitude: res.longitude
					},
					success: (res2) => {
						console.log(res2);
						// let data = res2.result.address_component
						// curAddress.value = res2.result.formatted_addresses.standard_address
						// console.log(data);
						// getDistrictByCityId(res2)
						// 获取区id
						getNowAreaByName(res2.result)
					},
					fail: (e) => {
						console.log(e, 'eee')
					}
				})

				// 获取附近房屋
			},
			fail: function (e) {
				// uni.setStorageSync('position_info', { code: 2, longitude: 0, latitude: 0 })
				console.log('获取位置信息失败：' + JSON.stringify(e));
			}
		});
	}
	const getNowAreaByName = async (e) => {

		let res = await proxy.$http("common.getNowAreaByName", { area_name: e.address_component.district, city_name: e.address_component.city })
		let data = res.data
		curAddress.value = data.province.name + '-' + data.cityInfo.name + '-' + data.areaInfo.name
		initCity(res.data)
	}
	// 区县相关
	const cityPickerShow = ref(false)
	const uCityPickerRef = ref(null)
	const rawCityData = ref([])
	const cityArr = ref([])
	const curAddress = ref('')
	const defaultIndex = ref([0, 3, 2])
	const positionInfo = ref({
		province_name: '',
		city_name: '',
		area_name: ''

	})
	const initCity = async (e) => {
		try {
			let res = await proxy.$http('common.getAreaAll')
			if (res.code === 1) {
				defaultIndex.value = []
				rawCityData.value = res.data
				positionInfo.value.province_name = e.province.name
				positionInfo.value.city_name = e.cityInfo.name
				positionInfo.value.area_name = e.areaInfo.name
				const provinceList = rawCityData.value.map(item => {
					return { name: item.name, id: item.id }
				})
				let provinceIndex = 0
				provinceList.forEach((v, index) => {
					if (v.id == e.province.id) {
						provinceIndex = index
						defaultIndex.value.push(index)
					}
				})
				const cityList = rawCityData.value[provinceIndex].children.map(item => {
					return { name: item.name, id: item.id }
				})
				let cityIndex = 0
				cityList.forEach((v, index) => {
					if (v.id == e.cityInfo.id) {
						defaultIndex.value.push(index)
						cityIndex = index
					}
				})
				const counties = rawCityData.value[provinceIndex].children[cityIndex].children.map(item => {
					return { name: item.name, id: item.id }
				})
				counties.forEach((v, index) => {
					if (v.id == e.areaInfo.id) {
						defaultIndex.value.push(index)
					}
				})
				console.log(defaultIndex.value);
				cityArr.value.push(provinceList, cityList, counties)
				getTaocan()
			} else {
				throw new Error(res.msg)
			}
		} catch (e) {
			uni.showToast({
				icon: 'none',
				title: e.message
			})
		}
	}
	const showCityPicker = () => {
		cityPickerShow.value = true
	}
	const cityPickerChangeHandler = (e) => {
		const { columnIndex, indexs } = e
		if (columnIndex === 0) {
			uCityPickerRef.value.setColumnValues(1, rawCityData.value[indexs[0]].children);
			uCityPickerRef.value.setColumnValues(2, rawCityData.value[indexs[0]].children[0].children);
		}
		if (columnIndex === 1) {
			uCityPickerRef.value.setColumnValues(2, rawCityData.value[indexs[0]].children[indexs[1]].children);
		}
	}
	const cityPickerConfirm = (e) => {
		const arr = []
		arr.push(e.value[0].name)
		arr.push(e.value[1].name)
		arr.push(e.value[2].name)
		curAddress.value = arr.join('-')
		positionInfo.value.province_name = e.value[0].name
		positionInfo.value.city_name = e.value[1].name
		positionInfo.value.area_name = e.value[2].name
		cityPickerShow.value = false
		getTaocan()
	}
</script>
<style lang="scss" scoped>
	.content {
		background: #F7F8FC;
		padding: 20rpx 32rpx;
		padding-bottom: 64rpx;

		.main {
			.sel_area {
				padding: 40rpx 20rpx;
				box-shadow: 2rpx 7rpx 5rpx 0rpx rgba(197, 197, 197, 0.29);
				border-radius: 12rpx;
				background: #ffffff;
			}

			.row1 {
				.row1_list {
					flex-wrap: wrap;

					.row1_item {
						width: 210rpx;
						height: 173rpx;
						box-shadow: 2rpx 7rpx 5rpx 0rpx rgba(197, 197, 197, 0.29);
						border-radius: 12rpx;
						display: flex;
						flex-direction: column;
						align-items: center;
						justify-content: center;
						background-size: 105.5% 109%;
						background-position: -6rpx -6rpx;
						background-repeat: no-repeat;
						border: 2rpx solid #ffffff;
					}

					.row1_item_active {
						border: 2rpx solid #FB845F;
					}

				}
			}

			.row2 {
				.row2_list {
					align-items: center;
					flex-wrap: wrap;
					display: flex;

					.row2_item {
						width: 154rpx;
						height: 154rpx;
						box-shadow: 2rpx 7rpx 5rpx 0rpx rgba(197, 197, 197, 0.29);
						border-radius: 12rpx;
						overflow: hidden;
						background-size: 106% 111%;
						background-position: -4rpx -6rpx;
						background-repeat: no-repeat;
						border: 2rpx solid #ffffff;

						.row2_item_title {
							height: 48rpx;
							// background: #EFEEEE;
							display: flex;
							align-items: center;
							justify-content: center;
						}

						.row2_item_main {
							height: 102rpx;
							display: flex;
							flex-direction: column;
							align-items: center;
							justify-content: center;
						}
					}

					.row2_item_active {
						border: 2rpx solid #FB845F;
					}
				}
			}
		}

		.aticon_box {
			width: 706rpx;
			height: 134rpx;
			padding: 0 22rpx;
			padding-bottom: 32rpx;
			background: #FFFFFF;
			box-shadow: 0rpx -5rpx 2rpx 0rpx rgba(105, 105, 105, 0.06);
			position: fixed;
			bottom: 0;
			left: 0;

			.aticon_right {
				.aticon_right_btn {
					width: 190rpx;
					height: 66rpx;
					background: #FD6C25;
					border-radius: 33rpx;
					display: flex;
					align-items: center;
					justify-content: center;
				}
			}
		}

	}

	::v-deep.u-image {
		display: flex;
		align-items: center;
	}
</style>